package com.zdy.viewpager;

import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem;

public class MaterialFragment extends Fragment {

	private FragmentActivity activity;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_materail_style, container,
				false);
	}

	protected PtrFrameLayout mPtrFrameLayout;
	private boolean mImageHasLoaded = false;
	private long mStartLoadingTime = -1;

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		activity = getActivity();
		int position = FragmentPagerItem.getPosition(getArguments());
		TextView title = (TextView) view.findViewById(R.id.item_title);
		title.setText(String.valueOf(position));
		mPtrFrameLayout = (PtrFrameLayout) view
				.findViewById(R.id.material_style_ptr_frame);

		// header
		final MaterialHeader header = new MaterialHeader(activity);
		int[] colors = getResources().getIntArray(R.array.google_colors);
		header.setColorSchemeColors(colors);
		header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
		header.setPtrFrameLayout(mPtrFrameLayout);

		mPtrFrameLayout.setLoadingMinTime(3000);
		mPtrFrameLayout.setDurationToCloseHeader(1500);
		mPtrFrameLayout.setHeaderView(header);
		mPtrFrameLayout.addPtrUIHandler(header);
		mPtrFrameLayout.postDelayed(new Runnable() {
			@Override
			public void run() {
				mPtrFrameLayout.autoRefresh(false);
			}
		}, 100);

		mPtrFrameLayout.setPtrHandler(new PtrHandler() {
			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				return true;
			}

			@Override
			public void onRefreshBegin(final PtrFrameLayout frame) {
				if (mImageHasLoaded) {
					long delay = (long) (1000 + Math.random() * 2000);
					delay = Math.max(0, delay);
					delay = 0;
					frame.postDelayed(new Runnable() {
						@Override
						public void run() {
							mImageHasLoaded = true;
							frame.refreshComplete();
						}
					}, delay);
				} else {
					mStartLoadingTime = System.currentTimeMillis();
				}
			}
		});

		mPtrFrameLayout.postDelayed(new Runnable() {
			@Override
			public void run() {
				mImageHasLoaded = true;
				mPtrFrameLayout.refreshComplete();
			}
		}, 5000);

	}

}
